<?php

include ('../functions/thumb.php');
include ('../functions/common.php');
include ('../functions/db.php');
$action = $_REQUEST['action'];

$parent_dir = dirname(dirname($_SERVER['SCRIPT_FILENAME']));

if ($action == 'profilslika') {
    if (isset($_FILES["file"]["name"]) && !empty($_FILES["file"]["name"])) {
        //if folder not exist create it
        $imagefolder = $parent_dir . '/media/autori/' . mres($_POST['username']) . '/slike_za_profil/';
        if (!is_dir($imagefolder))
            mkdir($imagefolder, 0777, true);
        $thumbfolder = $parent_dir . '/media/autori/thumbs/' . mres($_POST['username']) . '/slike_za_profil/';
        if (!is_dir($thumbfolder))
            mkdir($thumbfolder, 0777, true);

        $uploadStatus = upload_and_create_thumb($imagefolder, $thumbfolder);
        if ($uploadStatus == "Success") {
            updateProfilPicture($_FILES["file"]["name"], mres($_POST['username']));
            if (isset($_GET['redirect'])) {
                header("Location: ../?page=" . mres($_GET['redirect']));
            } else {
                header("Location: ../?page=nalog");
            }
        } else {
            echo $uploadStatus;
        }
        //else if slika is not selected
    } elseif (isset($_GET['redirect'])) {
        header("Location: ../?page=" . mres($_GET['redirect']));
    } else {
        header("Location: ../?page=nalog");
    }
} elseif ($action == 'dodaj_sliku') {
    //only upload
    $galerija = mres($_POST['galerija']);
    $username = mres($_POST['username']);
    $imagefolder = $parent_dir . '/media/autori/' . $username . '/';
    if (!is_dir($imagefolder))
        mkdir($imagefolder, 0777, true);
    $thumbfolder = $parent_dir . '/media/autori/thumbs/' . $username . '/';
    if (!is_dir($thumbfolder))
        mkdir($thumbfolder, 0777, true);
    $uploadStatus = upload_and_create_thumb($imagefolder, $thumbfolder);

    if ($uploadStatus == "Success") {
        //update ime slike u galeriju $_FILES["file"]["name"]
        header("Location: ../?page=upload_image&galerija=$galerija&file=" . $_FILES["file"]["name"]);
    } else {
        echo $uploadStatus;
    }
} elseif ($action == 'dodaj_sliku2') {
    //update database
    $naziv = mres($_POST['naziv']);
    $opis = mres($_POST['opis']);
    $kljucne_reci = mres($_POST['kljucne_reci']);
    $username = mres($_POST['username']);
    $slika = mres($_POST['slika']);
    $galerija = mres($_POST['galerija']);

    updateGalleryPicture($naziv, $opis, $kljucne_reci, $username, $slika, $galerija);
    header("Location: ../?page=nalog");
}
?>
